package com.moxiao.yfjh.module.order.controller.admin.brokeragewithdraw;

import cn.hutool.core.util.StrUtil;
import com.moxiao.yfjh.framework.common.pojo.CommonResult;
import com.moxiao.yfjh.framework.common.pojo.PageResult;
import com.moxiao.yfjh.framework.common.util.number.NoCommonUtil;
import com.moxiao.yfjh.framework.excel.core.util.ExcelUtils;
import com.moxiao.yfjh.framework.operatelog.core.annotations.OperateLog;
import com.moxiao.yfjh.framework.pay.core.enums.channel.PayChannelEnum;
import com.moxiao.yfjh.framework.pay.core.enums.transfer.PayTransferTypeEnum;
import com.moxiao.yfjh.module.blind.dal.dataobject.member.BlindMemberUserDO;
import com.moxiao.yfjh.module.blind.service.member.BlindMemberUserService;
import com.moxiao.yfjh.module.order.controller.admin.brokeragewithdraw.vo.*;
import com.moxiao.yfjh.module.order.convert.brokeragewithdraw.BlindBrokerageWithdrawConvert;
import com.moxiao.yfjh.module.order.dal.dataobject.brokeragewithdraw.BlindBrokerageWithdrawDO;
import com.moxiao.yfjh.module.order.tradeRefund.brokeragewithdraw.BlindBrokerageWithdrawService;
import com.moxiao.yfjh.module.pay.api.transfer.dto.PayTransferCreateReqDTO;
import com.moxiao.yfjh.module.pay.controller.admin.transfer.vo.PayTransferSubmitReqVO;
import com.moxiao.yfjh.module.pay.controller.admin.transfer.vo.PayTransferSubmitRespVO;
import com.moxiao.yfjh.module.pay.service.transfer.PayTransferService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.moxiao.yfjh.framework.common.pojo.CommonResult.success;
import static com.moxiao.yfjh.framework.common.util.servlet.ServletUtils.getClientIP;
import static com.moxiao.yfjh.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static com.moxiao.yfjh.module.order.enums.ErrorCodeConstants.WX_PAY_NOT_ORDER_EXISTS;
import static com.moxiao.yfjh.module.order.enums.ErrorCodeConstants.WX_PAY_USER_NOT_ORDER_EXISTS;

@Tag(name = "管理后台 - 相亲佣金提现")
@RestController
@RequestMapping("/order/brokerage-withdraw")
@Validated
public class BlindBrokerageWithdrawController {

    @Resource
    private BlindBrokerageWithdrawService brokerageWithdrawService;
    @Resource
    private BlindMemberUserService memberUserService;
    @Resource
    private PayTransferService payTransferService;

    @PostMapping("/create")
    @Operation(summary = "创建相亲佣金提现")
    @PreAuthorize("@ss.hasPermission('order:brokerage-withdraw:create')")
    public CommonResult<Long> createBrokerageWithdraw(@Valid @RequestBody BlindBrokerageWithdrawCreateReqVO createReqVO) {
        return success(brokerageWithdrawService.createBrokerageWithdraw(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "相亲佣金提现")
    @PreAuthorize("@ss.hasPermission('order:brokerage-withdraw:update')")
    public CommonResult<Boolean> updateBrokerageWithdraw(@Valid @RequestBody BlindBrokerageWithdrawUpdateReqVO updateReqVO) {
        brokerageWithdrawService.updateBrokerageWithdraw(updateReqVO);
        if (updateReqVO.getStatus() == 10) {
            // 同意退款，并创建退款转账
            PayTransferSubmitReqVO reqVO = new PayTransferSubmitReqVO();
            // 获得佣金提现的详情
            BlindBrokerageWithdrawDO withdrawDO = brokerageWithdrawService.getBrokerageWithdraw(updateReqVO.getId());
            // TODO 创建转账单
            PayTransferCreateReqDTO transferCreateReqDTO = new PayTransferCreateReqDTO();
            // TODO 内置写死 缘分相亲
            transferCreateReqDTO.setAppId(9L);
            transferCreateReqDTO.setMerchantOrderId(NoCommonUtil.getUuid(updateReqVO.getId().toString()).toString());
            // 将金额转成分
            BigDecimal cents = withdrawDO.getPrice().multiply(new BigDecimal("100"));
            int intValue = cents.intValue();
            transferCreateReqDTO.setPrice(intValue);
            transferCreateReqDTO.setTitle("佣金提现");

            BlindMemberUserDO userDO = memberUserService.getMemberUser(withdrawDO.getUserId());
            if (Objects.isNull(userDO)) {
                if (StringUtils.isNotBlank(userDO.getWxOpenId())) {
                    // 构建收款方信息
                    Map<String, String> payeeInfo = new HashMap<>();
                    payeeInfo.put("userName", userDO.getNickname());
                    transferCreateReqDTO.setPayeeInfo(payeeInfo);
                    if (withdrawDO.getType() == 3) {
                        reqVO.setChannelCode(PayChannelEnum.WX_TRANSFER.getCode());
                        transferCreateReqDTO.setType(PayTransferTypeEnum.WX_BALANCE.getType());
                        payeeInfo.put("openId", userDO.getWxOpenId());
                    } else if (withdrawDO.getType() == 4) {
                        reqVO.setChannelCode(PayChannelEnum.ALIPAY_TRANSFER.getCode());
                        transferCreateReqDTO.setType(PayTransferTypeEnum.ALIPAY_BALANCE.getType());
                        payeeInfo.put("openId", userDO.getZfbOpenId());
                    }
                    // 创建转账单
                    Long transferId = payTransferService.createTransfer(transferCreateReqDTO);

                    if (Objects.nonNull(transferId)) {
                        reqVO.setId(transferId);
                        // TODO 提交转账
                        PayTransferSubmitRespVO respVO = payTransferService.submitTransfer(reqVO, getClientIP());
                        System.out.println("提现转账成功：respVO:" + respVO);
                    }

                } else {
                    throw exception(WX_PAY_NOT_ORDER_EXISTS);
                }
            } else {
                throw exception(WX_PAY_USER_NOT_ORDER_EXISTS);
            }
        }
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除相亲佣金提现")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('order:brokerage-withdraw:delete')")
    public CommonResult<Boolean> deleteBrokerageWithdraw(@RequestParam("id") Long id) {
        brokerageWithdrawService.deleteBrokerageWithdraw(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得相亲佣金提现")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('order:brokerage-withdraw:query')")
    public CommonResult<BlindBrokerageWithdrawRespVO> getBrokerageWithdraw(@RequestParam("id") Long id) {
        BlindBrokerageWithdrawDO brokerageWithdraw = brokerageWithdrawService.getBrokerageWithdraw(id);
        BlindBrokerageWithdrawRespVO vo = BlindBrokerageWithdrawConvert.INSTANCE.convert(brokerageWithdraw);
        if (Objects.nonNull(vo)) {
            BlindMemberUserDO userDO = memberUserService.getMemberUser(vo.getUserId());
            if (Objects.nonNull(userDO)) {
                if (StrUtil.isNotBlank(userDO.getNickname())) {
                    vo.setNickName(userDO.getNickname());
                }
                if (StrUtil.isNotBlank(userDO.getMobile())) {
                    vo.setMobile(userDO.getMobile());
                }
            }
        }
        return success(vo);
    }

    @GetMapping("/list")
    @Operation(summary = "获得相亲佣金提现列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('order:brokerage-withdraw:query')")
    public CommonResult<List<BlindBrokerageWithdrawRespVO>> getBrokerageWithdrawList(@RequestParam("ids") Collection<Long> ids) {
        List<BlindBrokerageWithdrawDO> list = brokerageWithdrawService.getBrokerageWithdrawList(ids);
        return success(BlindBrokerageWithdrawConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得相亲佣金提现分页")
    @PreAuthorize("@ss.hasPermission('order:brokerage-withdraw:query')")
    public CommonResult<PageResult<BlindBrokerageWithdrawRespVO>> getBrokerageWithdrawPage(@Valid BlindBrokerageWithdrawPageReqVO pageVO) {
        PageResult<BlindBrokerageWithdrawRespVO> page = brokerageWithdrawService.selectJoinPage(pageVO);
        page.getList().forEach(item -> {

        });

        return success(page);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出相亲佣金提现 Excel")
    @PreAuthorize("@ss.hasPermission('order:brokerage-withdraw:export')")
    @OperateLog(type = EXPORT)
    public void exportBrokerageWithdrawExcel(@Valid BlindBrokerageWithdrawExportReqVO exportReqVO,
                                             HttpServletResponse response) throws IOException {
        List<BlindBrokerageWithdrawDO> list = brokerageWithdrawService.getBrokerageWithdrawList(exportReqVO);
        // 导出 Excel
        List<BlindBrokerageWithdrawExcelVO> datas = BlindBrokerageWithdrawConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "相亲佣金提现.xls", "数据", BlindBrokerageWithdrawExcelVO.class, datas);
    }

}
